/*
 * WordPress版同城信息发布
 * author: huangbin
 * 技术支持微信号：wxid_i8yk4fp0uep322
 * 开源协议：MIT
 *  *Copyright (c) 2018 https:/www.tczhb.club All rights reserved.
 */
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var auth = require('../../utils/auth.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js');
var app = getApp();
Page({
    data: {
        text: "Page topic",
        categoriesList: [],
        floatDisplay: "none"
    },
    onLoad: function (options) {
      wx.setNavigationBarTitle({
        title: app.globalData.app_name+'-发布'
      });
      if (!app.globalData.isGetOpenid) {
        auth.getUsreInfo();
      }
      this.fetchCategoriesData();
    },
    //获取分类列表
    fetchCategoriesData: function () {
      var self = this;
      //调用API从本地缓存中获取分类列表
      var categoryListArr = wx.getStorageSync('categoryList2') || [];
      if (categoryListArr.length > 0) {
        self.setData({
          floatDisplay: "block",
          categoriesList: categoryListArr
        });
      } 
      else {
        var getCategoriesRequest = wxRequest.getRequest(Api.getCategories(false));
        getCategoriesRequest.then(response => {
          if (response.statusCode === 200) {
            self.setData({
              floatDisplay: "block",
              categoriesList: self.data.categoriesList.concat(response.data.data.map(function (item) {
                if (typeof (item.more.thumbnail) == "undefined" || item.more.thumbnail == "") {
                  item.more.thumbnail = "../../images/website.png";
                }
                item.subimg = "subscription.png";
                return item;
              })),
            });
            wx.setStorageSync('categoryList2', self.data.categoriesList);
          }
          else {
            console.log(response);
          }
        })
        .then(res=>{
          if (!app.globalData.isGetOpenid) {
            self.getUsreInfo();
          }
        })
        .catch(function (response) {
            console.log(response);
        }).finally(function () {

        })
      }
    },
    getUsreInfo: function () {
        var self = this;
        var wxLogin = wxApi.wxLogin();
        var jscode = '';
        wxLogin().then(response => {
            jscode = response.code
            var wxGetUserInfo = wxApi.wxGetUserInfo();
            return wxGetUserInfo()
        }).
            //获取用户信息
            then(response => {
                console.log(response.userInfo);
                console.log("成功获取用户信息(公开信息)");
                app.globalData.userInfo = response.userInfo;
                app.globalData.isGetUserInfo = true;
                var url = Api.getOpenidUrl();
                var data = {
                    code: jscode,
                    encrypted_data: response.encryptedData,
                    iv: response.iv,
                    raw_data: response.rawData,
                    signature: response.signature
                }
                var postOpenidRequest = wxRequest.postRequest(url, data);
                //获取openid
                postOpenidRequest.then(response => {
                  if (response.statusCode === 200 && response.data.code === 200) {
                        console.log("openid 获取成功");
                        app.globalData.openid = response.data.data.openid;
                        app.globalData.isGetOpenid = true;
                        wx.setStorageSync('token', response.data.data.token);
                        app.globalData.uid = response.data.data.uid;
                    }
                    else {
                        console.log(response.data.message);
                    }
                  wx.hideLoading();
                })
            })
            .catch(function (error) {
                console.log('error: ' + error.errMsg);                
            })
    },
    //跳转至某分类下的文章列表
    redictIndex: function (e) {
        //console.log('查看某类别下的文章');  
        var id = e.currentTarget.dataset.id;
        var name = e.currentTarget.dataset.item;
        var url = '../list/list?categoryID=' + id;
        wx.navigateTo({
            url: url
        });
    },
    userAuthorization: function () {
        var self = this;
        // 判断是否是第一次授权，非第一次授权且授权失败则进行提醒
        wx.getSetting({
            success: function success(res) {
                console.log(res.authSetting);
                var authSetting = res.authSetting;
                if (util.isEmptyObject(authSetting)) {
                    console.log('第一次授权');
                } else {
                    console.log('不是第一次授权', authSetting);
                    // 没有授权的提醒
                    if (authSetting['scope.userInfo'] === false) {
                        wx.showModal({
                            title: '用户未授权',
                            content: '如需正常使用评论、点赞、赞赏等功能需授权获取用户信息。是否在授权管理中选中“用户信息”?',
                            showCancel: true,
                            cancelColor: '#296fd0',
                            confirmColor: '#296fd0',
                            confirmText: '设置权限',
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用户点击确定')
                                    wx.openSetting({
                                        success: function success(res) {
                                            console.log('打开设置', res.authSetting);
                                            var scopeUserInfo = res.authSetting["scope.userInfo"];
                                            if (scopeUserInfo) {
                                                self.getUsreInfo();
                                            }
                                        }
                                    });
                                }
                            }
                        })
                    }
                }
            }
        });
    },
    confirm: function () {
        this.setData({
            'dialog.hidden': true,
            'dialog.title': '',
            'dialog.content': ''
        })
    },
  // 跳转至发布详情页面
  redictPublish: function (e) {
    if (!app.globalData.isGetOpenid) {
      auth.getUsreInfo();
    }
    else{
      var id = e.currentTarget.dataset.id;
      var name = e.currentTarget.dataset.name;
      var url = '../publish/publish?id=' + id + '&name=' +name;
      wx.navigateTo({
        url: url
      })
    }
  },
  //跳转至拼车发布页面
  rredictCarPublish: function (e) {
    var url = '../publish/carPublish';
    wx.navigateTo({
      url: url
    })    
  }
})